<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>新增页面</title>
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
    <link rel="stylesheet" href="/app/admin/component/jsoneditor/css/jsoneditor.css" />
    <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
    <style>
        .selected_class{
            box-shadow: 3px 3px 6px rgba(85, 154, 227, 0.4);
            border: 2px solid #2d8cf0;
        }
        .ellipsis {
            overflow: hidden; /* 确保超出容器的文本被隐藏 */
            white-space: nowrap; /* 确保文本在一行内显示 */
            text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
        }
    </style>
</head>
<body>

<form class="layui-form" action="">

    <div class="mainBox">
        <div class="main-container mr-5">
            <div class="layui-form-item">
                <label class="layui-form-label required">角色名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" placeholder="" class="layui-input"  style="width: 46%">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <button type="button" class="pear-btn pear-btn-primary pear-btn-md select_tag">
                    选择角色特点
                </button>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">中文描述</label>
                <div class="layui-input-block">
                    <tip style="color: red;font-size: 12px;">多个特点，用英文逗号分开</tip>
                    <input type="text" name="analyze_content" placeholder="" class="layui-input">
                    <input type="hidden" name="select_tag">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">英文描述</label>
                <div class="layui-input-block">
                    <tip  style="color: red;font-size: 12px;">根据中文描述直接翻译过来，多个特点，用英文逗号分开</tip>
                    <input type="text" name="prompt" placeholder="" class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">性别</label>
                <div class="layui-input-block">
                    <input type="radio" name="sex" value="1" title="男"  lay-filter="sex" checked>
                    <input type="radio" name="sex" value="2" title="女"  lay-filter="sex" >
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">Lora</label>
                <div class="layui-input-block model_html"  style="display: flex;flex-direction: row;align-items: center;flex-wrap: wrap;">
                    <div class="model_click"  data-id="1" style="width: 100px;height: 120px;margin-right: 20px;">
                        <img src="https://ai-video-1320718644.cos.ap-guangzhou.myqcloud.com/video/local/stable_diffusion_image/20240513/png/0b52503b7725942befdf.png" style="width: 100px;height: 100px;">
                        <div>实打实大苏打</div>
                    </div>
                </div>
                <input type="hidden" name="rolaid" value="">
            </div>
            <div style="display: flex;flex-direction: row;align-items: center">
                <div class="layui-form-item" style="width: 95%">
                    <label class="layui-form-label">AI图像指令：</label>
                    <div class="layui-input-block">
                        <textarea name="ai_image_command" class="layui-textarea" rows="15" cols="100" style="width: 100%"><?=htmlspecialchars($ai_image_command)?></textarea>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <button type="button" class="pear-btn pear-btn-primary pear-btn-md"  lay-submit="" lay-filter="regenerate_image">
                    生成图片
                </button>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">角色预览：</label>
                <div class="layui-input-block ai_image_html"  style="display: flex;flex-direction: row;align-items: center">

                </div>
            </div>
        </div>
    </div>

    <div class="bottom">
        <div class="button-container">
            <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit=""
                    lay-filter="save">
                提交
            </button>
            <button type="reset" class="pear-btn pear-btn-md">
                重置
            </button>
        </div>
    </div>

</form>

<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/app/admin/component/jsoneditor/jsoneditor.js"></script>
<script src="/app/admin/admin/js/permission.js"></script>
<script src="/app/admin/admin/js/functions.js"></script>
<script src="/app/admin/admin/js/md5.js"></script>

<script>

    // 相关接口
    const PLANID = layui.url().search['planid'];
    const PRIMARY_KEY = "id";
    const PRIMARY_KEY_VALUE = layui.url().search[PRIMARY_KEY];
    const SELECT_API = "/app/admin/plan/role/select" + location.search;
    const UPDATE_API = "/app/admin/plan/role/update";
    const AI_REGENERATE_API = "/app/admin/plan/role/airegenerate";
    const PROGRESS_API = "/app/admin/index/getaiimageresult";
    const SELECT_TAG_URL = "/app/admin/plan/role/selecttag";

    layui.use(['element', 'jquery', 'drawer', 'layer', 'code'], function() {
        layui.$('.select_tag').click(function () {
            layui.drawer.open({
                legacy: false,
                title: ['选择角色特点', 'font-size:16px;color:#2d8cf0'],
                offset: 'r',
                area: "80%",
                maxmin: true,
                closeBtn: 1,
                iframe: SELECT_TAG_URL,
                end:function () {
                    //console.log('dasdasdas');
                }

            })
        })
    })

    // 获取数据库记录
    layui.use(["form", "util", "popup"], function () {
        $ = layui.$;
        $.ajax({
            url: SELECT_API,
            dataType: "json",
            async:true,
            headers: get_header({"id":PRIMARY_KEY_VALUE,"planid":PLANID}),
            success: function (res) {

                // 给表单初始化数据
                layui.each(res.data[0], function (key, value) {
                    let obj = $('*[name="'+key+'"]');
                    if (key === "password") {
                        obj.attr("placeholder", "不更新密码请留空");
                        return;
                    }
                    if (typeof obj[0] === "undefined" || !obj[0].nodeName) return;
                    if (obj[0].nodeName.toLowerCase() === "textarea") {
                        obj.val(value);
                    } else if ($(obj[0]).attr('type').toLowerCase() === "radio") {
                        $('input[name="'+key+'"]').each(function (i,v) {
                            if(value==$(this).val()){
                                $(this).attr("checked","checked");
                            }else{
                                $(this).removeAttr("checked");
                            }
                        })
                    }  else {
                        obj.attr("value", value);
                        obj[0].value = value;
                    }
                });
                if(res.data[0]['select_tag']){
                    layui.$('input[name="select_tag"]').val(encodeURIComponent(res.data[0]['select_tag']));
                    selectTag = JSON.parse(res.data[0]['select_tag']);
                }

                let html = '';
                if(res.data[0]['ai_images']){
                    var imgObj = new Image();                    //新建一个图片对象
                    imgObj.src = res.data[0]['ai_images'];                            //将图片的src属性赋值给新建图片对象的src
                    imgObj.onload = function () {
                        var size =  new Array(imgObj.width, imgObj.height);
                        size[1] = parseInt(200/size[0]*size[1])
                        html +='<img src="'+res.data[0]['ai_images']+'" onclick="open_image(this);" style="width: 200px;height: '+size[1]+'px;margin-right: 20px;">';
                        html +='<input type="hidden" name="ai_images" value="'+res.data[0]['ai_images']+'">';
                        layui.$('.ai_image_html').html(html);
                    }
                }

                getRolaList(res.data[0]['sex']);

                layui.form.on('radio(sex)', function(data){
                    getRolaList(data.value);
                });

                layui.form.render();

                // ajax返回失败
                if (res.code) {
                    layui.popup.failure(res.msg);
                }

            }
        });

    });

    //提交事件
    layui.use(["form", "popup","loading"], function () {
        // 字段验证允许为空
        layui.form.on("submit(save)", function (data) {
            let selectTags = layui.$('input[name="select_tag"]').val();
            if(selectTags){
                selectTags = decodeURIComponent(selectTags)
            }else{
                selectTags = '';
            }
            data.field['select_tag'] = selectTags;
            data.field['planid'] = PLANID;
            data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
            let loading = layer.load();
            layui.$.ajax({
                url: UPDATE_API,
                type: "POST",
                dateType: "json",
                data: data.field,
                async:true,
                headers: get_header(data.field),
                success: function (res) {
                    layer.close(loading);
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }
                    return layui.popup.success("操作成功", function () {
                        parent.refreshTable();
                        parent.layer.close(parent.layer.getFrameIndex(window.name));
                    });
                }
            });
            return false;
        });

        layui.form.on("submit(regenerate_prompt)", function (data) {
            data.field['type'] = 'regenerate_prompt';
            let loadIndex = layui.loading.Load(1, "生成中...");
            layui.$.ajax({
                url: AI_REGENERATE_API,
                type: "POST",
                dateType: "json",
                data: data.field,
                async:true,
                headers: get_header(data.field),
                success: function (res) {
                    layui.loading.loadRemove(1);
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }
                    return layui.popup.success("操作成功", function () {
                        layui.$('textarea[name="prompt"]').val(res.data.data);
                    });
                },
                error:function () {
                    layui.loading.loadRemove(1);
                    return layui.popup.failure('请求失败');
                }
            });
            return false;
        });

        layui.form.on("submit(regenerate_image)", function (data) {
            data.field['type'] = 'regenerate_image';
            data.field['nums'] = '1';
            data.field['planid'] = PLANID;
            let loadIndex = layui.loading.Load(1, "生成中...");
            layui.$.ajax({
                url: AI_REGENERATE_API,
                type: "POST",
                dateType: "json",
                data: data.field,
                async:true,
                headers: get_header(data.field),
                success: function (res) {
                    if (res.code) {
                        layui.loading.loadRemove(1);
                        return layui.popup.failure(res.msg);
                    }
                    let requestid = res.data.requestid;
                    let timer = setInterval(function(){
                        layui.$.ajax({
                            url: PROGRESS_API+'?requestid='+requestid,
                            dataType: "json",
                            type: "get",
                            async: true,
                            headers: get_header({"requestid": requestid}),
                            success: function (res2) {
                                if (res2.code) {
                                    layui.loading.loadRemove(1);
                                    clearInterval(timer);
                                    return layui.popup.failure(res2.msg);
                                } else {
                                    let images = res2.data.images
                                    if(images.length>0){
                                        layui.loading.loadRemove(1);
                                        clearInterval(timer);
                                        return layui.popup.success("操作成功", function () {
                                            let html = '';
                                            layui.$.each(images,function (i,v) {
                                                html +='<img src="'+v+'" onclick="open_image(this);" style="width: 200px;height: 265px;margin-right: 20px;">';
                                                html +='<input type="hidden" name="ai_images" value="'+v+'">';
                                            })
                                            layui.$('.ai_image_html').html(html);
                                        });
                                    }
                                }
                            }
                        });
                    }, 30000);
                },
                error:function () {
                    layui.loading.loadRemove(1);
                    return layui.popup.failure('请求失败');
                }
            });
            return false;
        });
    });

    function getRolaList(sex) {
        // 字段 商家 business_id
        layui.use(["jquery", "xmSelect", "popup"], function() {
            layui.$.ajax({
                url: "/app/admin/image/rola/select?limit=1000&status=1&sex="+sex,
                dataType: "json",
                async:true,
                headers: get_header({"status":"1","sex":sex}),
                success: function (res2) {
                    let html = '';
                    let rolaid = layui.$('input[name="rolaid"]').val();
                    layui.$.each(res2.data,function (i,v) {
                        let selected = '';
                        if(rolaid==v.id){
                            selected = 'selected_class';
                        }
                        html += ' <div class="model_click '+selected+'" data-id="'+v.id+'" style="width: 100px;height: 120px;margin-right: 20px;">\n' +
                            '           <img src="'+v.image+'" style="width: 100px;height: 100px;" title="'+v.rola+'">\n' +
                            '           <div class="ellipsis">'+v.name+'</div>\n' +
                            '  </div>';
                    })
                    layui.$('.model_html').html(html);
                    if (res2.code) {
                        layui.popup.failure(res2.msg);
                    }
                }
            });

            layui.$('.model_html').delegate('.model_click','click',function () {
                layui.$('.model_click').removeClass('selected_class');
                layui.$(this).addClass('selected_class');
                layui.$('input[name="rolaid"]').val(layui.$(this).data('id'));
                //console.log($(this).data('id'));
            })
        });
    }
</script>

</body>
</html>
